//
//  PushHouseInfoViewController.m
//  Liuhe
//
//  Created by zr on 2018/8/9.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "PushHouseInfoViewController.h"
#import "PushRentHouseHeader.h"
#import "PushInfoTableViewCell.h"
#import "InfoOthersTableViewCell.h"

@interface PushHouseInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    
    UIImagePickerController *_imagePickerController;
}

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSArray * titleArray;
@property (nonatomic, strong)NSArray * textFiledArray;
@property (nonatomic, weak)UIButton * commitButton;
@property (nonatomic, strong)PushRentHouseHeader * header;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, copy)NSString * images;
//textFiled 数据
@property (nonatomic, copy)NSString * categoryStr;
@property (nonatomic, copy)NSString * rentMoneyStr;
@property (nonatomic, copy)NSString * areStr;
@property (nonatomic, copy)NSString * houseStr;
@property (nonatomic, copy)NSString * nameStr;
@property (nonatomic, copy)NSString * adressStr;
@property (nonatomic, copy)NSString * titleStr;
@property (nonatomic, copy)NSString * exploreStr;
@property (nonatomic, copy)NSString * telStr;
@property (nonatomic, copy)NSString * personStr;


@end

@implementation PushHouseInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = WHITE_COLOR;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addPictureToPushHouse) name:@"addPictureToPushHouse" object:nil];
    
    self.titleArray = @[@"发布类型:",@"租金:",@"面积:",@"户型:",@"小区名称:",@"详细地址:",@"标题:",@"详情描述:",@"联系电话:",@"联系人:"];
    self.textFiledArray = @[@"出租2 卖1",@"元/月",@"平方",@"室、厅、卫",@"请输入",@"5-30个字符",@"5-30个字符",@"",@"座机或者手机号",@"请填写联系人"];
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    [self setupNav];
    [self setupUI];
    [self setupAlertVC];
}


- (void)setupNav{
    
    self.title = @"发布信息";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(0, 0, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
}

- (void)backToView{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)setupUI{
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT - 64 - 100 * SCREENH6) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.rowHeight = 90 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[PushInfoTableViewCell class] forCellReuseIdentifier:@"PushHouseOneListCell"];
    [self.tableView registerClass:[InfoOthersTableViewCell class] forCellReuseIdentifier:@"PushHouseTwoListCell"];
    [self.tableView registerClass:[PushRentHouseHeader class] forHeaderFooterViewReuseIdentifier:@"PushRentHouseHeader"];
    
    [self.view addSubview:self.tableView];
    
    
    UIButton * commitButton = [UIButton new];
    
    [commitButton setTitle:@"立即提交" forState:UIControlStateNormal];
    [commitButton setBackgroundColor:MAINCOLOR];
    [commitButton setTitleColor:WHITE_COLOR forState:UIControlStateNormal];
    commitButton.titleLabel.font = [UIFont systemFontOfSize:17 * SCREENH6];
    [commitButton addTarget:self action:@selector(clickCommitButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.commitButton = commitButton;
    
    [self.view addSubview:self.commitButton];
}


- (void)viewDidLayoutSubviews{
    
    [self.commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(50 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-50 * SCREENH6);
        make.top.mas_equalTo(self.tableView.mas_bottom).offset(30 * SCREENH6);
        make.height.mas_equalTo(50 * SCREENH6);
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return 10;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 7) {
        
        InfoOthersTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PushHouseTwoListCell" forIndexPath:indexPath];
        
        cell.block = ^(NSString * text) {
            
            self.exploreStr = text;
        };
        
        cell.titleLabel.text = self.titleArray[indexPath.row];
        
        return cell;
        
    }else{
        
        PushInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PushHouseOneListCell" forIndexPath:indexPath];
        
        cell.titleLabel.text = self.titleArray[indexPath.row];
        cell.textFiled.placeholder = self.textFiledArray[indexPath.row];
        
        if (indexPath.row == 0) {
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.categoryStr = text;
            };
        } else if (indexPath.row == 1) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.rentMoneyStr = text;
            };
        } else if (indexPath.row == 2) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.areStr = text;
            };
        }else if (indexPath.row == 3) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.houseStr = text;
            };
        }else if (indexPath.row == 4) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.nameStr = text;
            };
        }else if (indexPath.row == 5) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.adressStr = text;
            };
        }else if (indexPath.row == 6) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.titleStr = text;
            };
        }else if (indexPath.row == 8) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.telStr = text;
            };
        }else if (indexPath.row == 9) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.personStr = text;
            };
        }
        
        return cell;
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 7) {
        
        return 133 * SCREENH6;
    }else{
        
        return 45 * SCREENH6;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 125 * SCREENH6;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    self.header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"PushRentHouseHeader"];
    
    return self.header;
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo

{
    
    [self.header.addPictureButton setImage:image forState:UIControlStateNormal];
    
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.5);
    
    NSString * token = DEF_GET_OBJECT(@"token");
    
    NSDictionary * dic = @{@"files":frontImageData,@"token":token};
    
    [[NetworkTool sharedTools] POST:@"/index/Note/noteupload" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat  = @"yyyyMMddHHmmss";
        NSString *str  = [formatter stringFromDate:[NSDate date]];
        NSString *fileName  = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:frontImageData name:@"files" fileName:fileName mimeType:@"image/png"];
        
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        NSLog(@"===%@",responseObject);
        
        NSInteger code = [responseObject[@"status"] integerValue];
        
        if (code == 200){
            
            self.images = [NSString stringWithFormat:@"%@",responseObject[@"data"]];
        }else{
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//进入拍摄页面点击取消按钮

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)addPictureToPushHouse{
    
    [self presentViewController:self.alertVC animated:YES completion:nil];
}


- (void)clickCommitButton{
    
    SHOWHUD;
    
    NSString * token = DEF_GET_OBJECT(@"token");
    
    NSDictionary * dict = @{@"token":token,@"type":self.categoryStr,@"images":self.images,@"price":self.rentMoneyStr,@"region":self.adressStr,@"decorate":@"精装",@"area":self.self.areStr,@"room":self.houseStr,@"name":self.nameStr,@"address":self.adressStr,@"describe":self.exploreStr,@"contact":self.personStr,@"phone":self.telStr,@"hall":@"2"};
    
    [[NetworkTool sharedTools] POST:@"/index/Liuheonline/leaseAdd" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
         HIDDENHUD;
        
        int code = [responseObject[@"status"] intValue];
        
        if (code == 200) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"恭喜你，发布成功，快去看看吧！"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"msg"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        HIDDENHUD;
        
        NSLog(@"error==%@",error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
